package com.sy.simpleegg.util

import android.graphics.Bitmap
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import java.util.Hashtable

object QRCodeUtil {
    fun createQRCode(content: String?, width: Int, height: Int): Bitmap? {
        return createQRCode(content, width, height, Color.BLACK, Color.WHITE)
    }

    /**
     * 创建二维码
     */
    private fun createQRCode(
        content: String?,
        width: Int,
        height: Int,
        codeColor: Int,
        codeBac: Int,
    ): Bitmap? {
        val hints = Hashtable<EncodeHintType, String>()
        hints[EncodeHintType.MARGIN] = "1"
        return createQRCode(content, width, height, codeColor, codeBac, hints)
    }

    /**
     * 创建二维码
     */
    private fun createQRCode(
        content: String?,
        width: Int,
        height: Int,
        codeColor: Int,
        codeBac: Int,
        hints: Hashtable<EncodeHintType,String>?,
    ): Bitmap? {
        try {
            val matrix = QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints)
            val pixels = IntArray(width * height)
            for (y in 0 until height) {
                for (x in 0 until width) {
                    if (matrix[x, y]) {
                        //二维码显示部分
                        pixels[y * width + x] = codeColor
                    } else {
                        //二维码背景
                        pixels[y * width + x] = codeBac
                    }
                }
            }
            return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }
}